package com.cola.xml;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;
import org.apache.commons.collections.functors.IfClosure;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.session.IoEventType;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.print.Doc;
import javax.swing.*;
import javax.swing.text.StyledEditorKit;
import javax.xml.parsers.*;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.lang.annotation.Retention;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TransferQueue;

/**
 * @Grup:com.cola.xml
 * @Auther:cola
 * @Data:2021/4/10-2021-04-12:14
 * @version:1.0
 *
 * SAX解析的特点
 * 1.基于事件驱动
 * 2.顺序读取,速度快
 * 3.不能任意读取节点,(灵活性)
 * 4.解析时占用的内存小
 * 5.SAX更适用于性能要求更高的设备上使用(Android开发中)
 *
 * DOM解析XML
 * 1.基于树形
 *
 *
 * JDOM解析XML
 */

public class xmlDemo {
    /*
    * 使用第三方Xstream组件实现XML的解析与生成
    * */
    @Test
    public void xStream(){
        person p=new person();
        p.setPersonid("1212");
        p.setAddress("北京");
        p.setTel("(24)548787");
        p.setFax("(47)6468464");
        p.setEmail("1064522588@qq.com");
        p.setName("77");

        XStream xStream = new XStream(new Xpp3Driver());
        xStream.alias("person",person.class);
        xStream.useAttributeFor(person.class,"personid");
        String xml = xStream.toXML(p);
        System.out.println(xml);

        //解析XML
        person person=(person)xStream.fromXML(xml);
        System.out.println(person);
    }

    @Test
    public void  xmlDeCode(){
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\cola\\IdeaProjects\\MyJavaStudy\\XmlAndJson17\\src\\main\\resources\\test.xml"));
            XMLDecoder decoder=new XMLDecoder(bis);
            person p=(person) decoder.readObject();
            System.out.println(p);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    /*
    * 把对象转成XML文件
    *
    * */
    @Test
    public void xmlEnCode(){
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\cola\\IdeaProjects\\MyJavaStudy\\XmlAndJson17\\src\\main\\resources\\test.xml"));
            XMLEncoder xmlEncoder=new XMLEncoder(bos);
            person p=new person();
            p.setPersonid("1212");
            p.setAddress("北京");
            p.setTel("(24)548787");
            p.setFax("(47)6468464");
            p.setEmail("1064522588@qq.com");
            p.setName("77");
            xmlEncoder.writeObject(p);
            xmlEncoder.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void dom4jparseXML(){
        //创建dom4j的解析器对象
        SAXReader reader=new SAXReader();
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("person.xml");
        person p=null;
        ArrayList<person> pensons=new ArrayList<>();
        try {
            org.dom4j.Document doc = reader.read(is);
            org.dom4j.Element rootElement = doc.getRootElement();
            Iterator<org.dom4j.Element> iterator = rootElement.elementIterator();
            while (iterator.hasNext()){
                p=new person();
                org.dom4j.Element e = iterator.next();
                p.setPersonid(e.attributeValue("personid"));
                Iterator<org.dom4j.Element> iterator1 = e.elementIterator();
                while (iterator1.hasNext()){
                    org.dom4j.Element next = iterator1.next();
                    String tag = next.getName();
                    if ("name".equals(tag)){
                        p.setName(next.getText());
                    }else if ("addtess".equals(tag)){
                        p.setAddress(next.getText());
                    }else if ("tel".equals(tag)){
                        p.setTel(next.getText());
                    }else if ("fax".equals(tag)){
                        p.setFax(next.getText());
                    }else if ("email".equals(tag)){
                        p.setEmail(next.getText());
                    }
                }
                pensons.add(p);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        System.out.println("结果:");
        System.out.println(Arrays.toString(pensons.toArray()));
    }
    @Test
    public void jdomPardeXML(){
        //创建JDOM解析器
        SAXBuilder builder =new SAXBuilder();
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("person.xml");
        List<person> list = null;
        try {
            org.jdom.Document build = builder.build(is);
            Element rootElement = build.getRootElement();

            list = new ArrayList<>();
            person person=null;
            List<Element> children=rootElement.getChildren();
            for (Element element :children) {
                person =new person();
                String personid = element.getAttributeValue("personid");
                person.setPersonid(personid);
                List<Element> children1 = element.getChildren();
                for (Element e :children1){
                    String tag = e.getName();
                    if ("name".equals(tag)){
                        person.setName(e.getText());
                    }else if ("addtess".equals(tag)){
                        person.setAddress(tag);
                    }else if ("tel".equals(tag)){
                        person.setTel(e.getText());
                    }else if ("fax".equals(tag)){
                        person.setFax(e.getText());
                    }else if ("email".equals(tag)){
                        person.setEmail(e.getText());
                    }
                }
                list.add(person);
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("结果:");
        System.out.println(Arrays.toString(list.toArray()));
    }
    @Test
    public void domParseXML(){
        //1.创建一个DOM解析器工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //2.通过工厂创建解析器对象
        DocumentBuilder documentBuilder = null;
        try {
            documentBuilder= documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //3.解析文档
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("person.xml");
        //此代码完成后,整个XML文档已经被加载到内存中,以树状形式存储
        Document doc=null;
        try {
             doc = documentBuilder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.从内存中读取数据

        NodeList personNodeList = doc.getElementsByTagName("person");
        ArrayList<person> persons=new ArrayList<>();
        person p=null;
        for (int i = 0; i <personNodeList.getLength() ; i++) {
            Node personNode = personNodeList.item(i);
            p=new person();
            String personid = personNode.getAttributes().getNamedItem("personid").getNodeValue();
            p.setPersonid(personid);
            //获取当前节点的子节点
            NodeList childNodes = personNode.getChildNodes();
            for (int j = 0; j <childNodes.getLength() ; j++) {
                Node item = childNodes.item(j);
                String nodeName = item.getNodeName();
                if ("name".equals(nodeName)){
                    p.setName(item.getFirstChild().getNodeValue());
                }else if ("address".equals(nodeName)){
                    p.setAddress(item.getFirstChild().getNodeValue());
                }else if ("tel".equals(nodeName)){
                    p.setTel(item.getFirstChild().getNodeValue());
                }else if ("fax".equals(nodeName)){
                    p.setFax(item.getFirstChild().getNodeValue());
                }else if ("email".equals(nodeName)){
                    p.setEmail(item.getFirstChild().getNodeValue());
                }
            }
            persons.add(p);
        }
        System.out.println("结果:");
        System.out.println(Arrays.toString(persons.toArray()));
    }

    @Test
    public void saxParseXML(){
        //1.创建一个SAX解析器工厂对象
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        //2.通过工厂对象创建SAX解析器
        SAXParser saxParser=null;
        try {
            saxParser = saxParserFactory.newSAXParser();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        //3.创建一个数据处理器(需要我们自己来编写)
        personHandler personHandler = new personHandler();
        //4.开始解析
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("person.xml");
        try {
            saxParser.parse(is,personHandler);
            List<person> persons=personHandler.getPersons();
            for (person p :
                    persons) {
                System.out.println(p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
